package com.ws.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.ws.common.CommonResult;
import com.ws.util.JWTUtil;
@Component
public class LoginInterceptor implements HandlerInterceptor{
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		//在处理handler之前  返回true 可以执行对应的handler  返回false 执行不到handler
		//return true/false 是springMvc中的运行路线  不是回应给浏览器的
		/*
		 * 验证每个请求是否是登录状态
		 * 怎么样是登录状态  有token  token有效
		 * token在哪？ 在headers中
		 */
		String token = request.getHeader("authorization");
		System.out.println("token:" + token );
		if(token != null && JWTUtil.verifyToken(token)) {
			//有token并且token有效  是登录状态
			return true;
		}else {
			//要回应给浏览器的数据
			CommonResult result = CommonResult.fail(400,"weidenglu");
			//将数据解析成JSON
			String json = JSON.toJSONString(result);
			//将数据的json格式返回给前端
			response.getWriter().write(json);
			return false;
		}
		
		
	}
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
		HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
	}
	//
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		
		HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
	}
}
